<template>
    <div class="edit-dialog-container">
        <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" destroy-on-close>
            <el-tabs type="border-card">
                <el-tab-pane label="基础信息">
                    <el-form ref="dialogFormRef" :model="state.content" :rules="formRules" size="default"
                        label-width="90px">
                        <el-row :gutter="35">
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                <el-form-item prop="code" label="工号">
                                    <el-input v-model="state.content.code" :disabled="state.dialog.type === 1"
                                        placeholder="请输入用户工号" clearable></el-input>
                                </el-form-item>
                                <el-form-item prop="name" label="用户姓名">
                                    <el-input v-model="state.content.name" placeholder="请输入用户姓名" clearable></el-input>
                                </el-form-item>
                                <el-form-item prop="icCode" label="卡号">
                                    <el-input v-model="state.content.icCode" placeholder="请输入卡号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <el-form-item label="照片头像">
                                    <el-tooltip placement="top">
                                        <template #content>点击预览头像</template>
                                        <el-image
                                            style="width: 90px; height:90px;border: 1px dashed #ccc;box-sizing: border-box;"
                                            class="image-show"
                                            :preview-src-list="[`data:image/jpg;base64,${state.content.avatar}`]"
                                            :src="`data:image/jpg;base64,${state.content.avatar}`">
                                            <template #error>
                                                <div class="image-slot">
                                                    暂无头像
                                                </div>
                                            </template>
                                        </el-image>
                                    </el-tooltip>
                                    <el-tooltip placement="top">
                                        <template #content>点击预览人脸照片</template>
                                        <el-image
                                            style="width: 90px; height: 90px;border: 1px dashed #ccc;box-sizing: border-box;margin-left: 5px;"
                                            class="image-show"
                                            :preview-src-list="[`data:image/jpg;base64,${state.content.biophoto}`]"
                                            :src="`data:image/jpg;base64,${state.content.biophoto}`">
                                            <template #error>
                                                <div class="image-slot">
                                                    暂无人脸照片
                                                </div>
                                            </template>
                                        </el-image>
                                    </el-tooltip>
                                    <el-row>
                                        <el-upload :show-file-list="false" action="" :before-upload="beforeAvatarUpload"
                                            style="margin-left: 24px;">
                                            <el-button type="primary" size="small">
                                                {{$t('message.btnName.upload')}}
                                            </el-button>
                                        </el-upload>
                                        <el-upload style="margin-left: 45px;" :show-file-list="false" action=""
                                            :before-upload="beforeBiophotoUpload">
                                            <el-button type="success" size="small">
                                                {{$t('message.btnName.upload')}}
                                            </el-button>
                                        </el-upload>
                                    </el-row>
                                </el-form-item>
                            </el-col>
                            <el-divider>
                                <el-icon><star-filled /></el-icon>
                            </el-divider>
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                <el-form-item label="部门" prop="orgCode">
                                    <el-tree-select v-model="state.content.orgCode" :data="orgList" value-key="code"
                                        check-strictly :render-after-expand="false" clearable
                                        :props="{ label: 'name', children: 'children' }" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                <el-form-item label="角色" prop="roleCode">
                                    <el-select size="default" v-model="state.content.roleCode" placeholder="请选择角色"
                                        clearable>
                                        <el-option v-for="item in roleList" :label="item.name"
                                            :value="item.code"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                <el-form-item label="设备权限" prop="privilege">
                                    <el-select size="default" v-model="state.content.privilege" placeholder="设备权限"
                                        clearable>
                                        <el-option label="普通用户" :value="0"></el-option>
                                        <el-option label="管理员" :value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                <el-form-item prop="emergPwd" label="设备密码">
                                    <el-input v-model="state.content.emergPwd" placeholder="请输入设备密码" show-password
                                        type="password"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-divider>
                                <el-icon><star-filled /></el-icon>
                            </el-divider>
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"
                                v-for="item in state.dictConfig">
                                <el-form-item :label="item.title" style="align-items: center;">
                                    <el-radio-group v-if="item.label === 1" class="ml-4" v-model="item.defaultOption">
                                        <el-radio v-for="optItem in item.options" :label="optItem" size="large"></el-radio>
                                    </el-radio-group>
                                    <el-checkbox-group v-if="item.label === 2" v-model="item.defaultOptions">
                                        <el-checkbox v-for="optItem in item.options" :label="optItem" border />
                                    </el-checkbox-group>
                                    <el-input v-if="item.label === 3" v-model="item.defaultOption"
                                        :placeholder="`请输入${item.title}`" clearable></el-input>
                                    <el-select v-if="item.label === 4" v-model="item.defaultOption" clearable>
                                        <el-option v-for="optItem in item.options" :label="optItem"
                                            :value="optItem"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="门禁权限" style="height: 384px;">
                    <el-row :gutter="35">
                        <el-table :data="state.content.accessCasbinList" border style="width: 100%">
                            <el-table-column prop="rule.ruleName" label="规则名称" />
                            <el-table-column prop="name" label="授权方式">
                                <template #default="{ row }">
                                    {{ row.pType === 'rule' ? '按人员添加' :
                                        row.pType === 'org' ? '按照部门授权' : '按照角色授权'
                                    }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="生物模板采集" style="height: 384px;">
                    <el-row :gutter="35">
                        <el-tag style="margin-left: 5px;" type="error">未识别到高拍仪驱动</el-tag>
                        <el-tag class="ml-2" type="error" style="margin-left: 5px;">未识别到指纹仪驱动</el-tag>
                    </el-row>
                </el-tab-pane>
            </el-tabs>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onSubmitContinue" type="primary" size="default" v-if="state.dialog.type === 0">{{
                        t('message.btnName.continueSubmit')
                    }}</el-button>
                    <el-button @click="onSubmit" type="success" size="default">{{ t('message.btnName.submit')
                    }}</el-button>
                    <el-button @click="onCancel" size="default">{{ t('message.btnName.cancel') }}</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" >
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, UploadProps, messageConfig } from 'element-plus';
import { fileToBase64 } from '/@/utils/files';
import { usePersonDictPageApi } from '/@/api/person/dict';
import { usePersonEmployeeCreateApi, usePersonEmployeeQueryApi, usePersonEmployeeUpdateApi, useValidBiophotoApi } from '/@/api/person/employee';
import { usePersonRoleListApi } from '/@/api/person/role';
import { usePersonOrgTreeApi } from '/@/api/person/org';
import { StarFilled } from '@element-plus/icons-vue'

// 定义子组件向父组件传值/事件
const { t } = useI18n();
const emit = defineEmits(['refresh']);

// 定义变量内容
const dialogFormRef = ref();
const orgList = ref<any[]>([])
const roleList = ref<any[]>([])

const useContent = () => {
    return {
        code: '', // 账户名称
        name: '', // 用户姓名
        remark: '', // 邮箱
        password: '', // 账户密码
        newPassword: '',
        icCode:'',
        privilege: 0,
        emergPwd: '',
        avatar: '',
        redirect: '',
        orgCode: '1',
        roleCode: '1',
    }
}

const state = reactive({
    content: {} as any,
    dictConfig: [] as any,
    dialog: {
        isShowDialog: false,
        type: 0,
        title: '',
    },
});

//头像
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
    if (!rawFile.type.includes('image')) {
        ElMessage.error('图片格式不正确!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('图片不能大于 1MB!')
        return false
    }
    fileToBase64(rawFile).then((res) => {
        state.content.avatar = res as string
    })
    return true
}

//人脸
const beforeBiophotoUpload: UploadProps['beforeUpload'] = rawFile => {
    console.log(rawFile.type, 'type')
    if (!rawFile.type.includes('image')) {
        ElMessage.error('图片格式不正确!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('图片不能大于 1MB!')
        return false
    }
    fileToBase64(rawFile).then((res) => {
        useValidBiophotoApi({ bitphoto: res }).then(({ content }) => {
            state.content.biophoto = res as string
            ElMessage.success('人脸照片校验成功');
        })

    })
    return true
}

// 表单校验
const formRules = ref({
    code: [
        { required: true, message: '必填项不能为空', trigger: 'blur' },
        { min: 1, max: 48, message: '工号必须1-9位字母数字组合而成', trigger: 'blur' },
        { pattern: /^[a-z0-9]/, message: '工号必须非0数字或小写字母开头', trigger: 'blur' },
    ],
    name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
    // dict: [{ validator: true, message: '必填项不能为空', trigger: 'blur' }],
    orgCode: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
    roleCode: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
    mobile: [{ pattern: /^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/, message: '请输入正确手机号', trigger: 'blur' },],
})

// 打开弹窗
const openDialog = (code?: string) => {
    state.dialog.isShowDialog = true
    // 获取字典列表
    usePersonDictPageApi({ pageNum: 1, pageSize: 20 }).then(({ content }) => {
        state.dictConfig = content.list
    })
    // 获取信息
    if (code) {
        state.dialog.title = t('message.btnName.edit')
        state.dialog.type = 1
        usePersonEmployeeQueryApi(code).then(({ content }) => {
            state.content = content
        }).then(() => {
            // 扩展属性赋值
            state.content.dictInfo.forEach((userDictItem: { title: string, valuable: string, valuables: [] }) => {
                state.dictConfig.forEach((dictConfigItem: any) => {
                    if (userDictItem.title === dictConfigItem.title) {
                        dictConfigItem.defaultOption = userDictItem.valuable
                        dictConfigItem.defaultOptions = userDictItem.valuables
                        console.log(userDictItem);
                    }
                    return dictConfigItem
                })
            })
        })
    } else {
        state.dialog.title = t('message.btnName.addRow')
        state.dialog.type = 0
        state.content = useContent()
    }
    getOrgCodes()
    getRoleCodes()
};

// 关闭弹窗
const closeDialog = () => {
    state.dialog.isShowDialog = false;
    state.content = useContent()
    emit('refresh');
};
// 取消
const onCancel = () => {
    closeDialog();
};

// 提交
const onSubmit = () => {
    dialogFormRef.value.validate((valid: boolean) => {
        if (!valid) {
            return false
        }
        let formData = Object.assign({}, state.content);
        formData.dictInfo = []
        state.dictConfig.forEach((item: {
            title: string; defaultOption: any; defaultOptions: any;
        }) => {
            formData.dictInfo.push({
                title: item.title,
                valuable: item.defaultOption,
                valuables: item.defaultOptions
            })
        })
        if (state.dialog.type === 1) {
            usePersonEmployeeUpdateApi(formData).then(() => {
                ElMessage({
                    type: 'success',
                    message: '操作成功'
                })
                closeDialog()
            })
        } else {
            usePersonEmployeeCreateApi(formData).then(() => {
                ElMessage({
                    type: 'success',
                    message: '操作成功'
                })
                closeDialog()
                console.log(state.content);
            })
        }

    })
};
// 提交
const onSubmitContinue = () => {
    dialogFormRef.value.validate((valid: boolean) => {
        if (!valid) {
            return false
        }

        let formData = Object.assign({}, state.content);
        formData.dictInfo = []
        state.dictConfig.forEach((item: { title: any; defaultOption: any; defaultOptions: any; }) => {
            formData.dictInfo.push({
                title: item.title,
                valuable: item.defaultOption,
                valuables: item.defaultOptions
            })
        })
        usePersonEmployeeCreateApi(formData).then(() => {
            ElMessage({
                type: 'success',
                message: '操作成功'
            })
            state.content.code = ''
            state.content.name = ''
        })
    });
};

const getOrgCodes = () => {
    usePersonOrgTreeApi().then(({ content }) => {
        orgList.value = content
    })
}

const getRoleCodes = () => {
    usePersonRoleListApi().then(({ content }) => {
        roleList.value = content
    })
}


defineExpose({
    openDialog,
});
</script>


<style scoped lang="scss">
:deep(.el-dialog__header) {
    margin: 0;
    border-bottom: 1px dashed rgba(0, 0, 0, .2);
}

:deep(.el-dialog__footer) {
    border-top: 1px dashed rgba(0, 0, 0, .2);
}
</style>